﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Text.RegularExpressions;

namespace Yosca
{
	/// <summary>
	/// Interaction logic for emailClient.xaml
	/// </summary>
	public partial class emailClient : Window
	{
        PrintEstimate document;
        String filepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\invoice.xps";  // specify attachment file path
		public emailClient(PrintEstimate doc, String clientEmail)
		{
			this.InitializeComponent();
            document = doc;
			clearFields();
			toBox.Text = clientEmail;
			
			MessageBox.Show("Document is attatched");
		}
		
		private void sendMail()
		{
			
			String mailFrom = usernameBox.Text;
            String mailTo = toBox.Text;
            String subject = subjectBox.Text;
            String body = messageBody.Text;
            String usrName = usernameBox.Text;  // specify email username
            String pass = passwordBox.Password; // specify email password
            String hostname = getHost(); // specify email service
            
 
            // Create the message object.
            if (verifyEmail(usernameBox.Text) == false || verifyEmail(toBox.Text) == false || passwordBox.Password == "" ||  subjectBox.Text == "" || messageBody.Text == "")
            {
                MessageBox.Show("Please fill all fields appropriately.");
                return;
            }


             MailMessage message = new MailMessage(mailFrom, mailTo, subject, body);
            
            
             
            // Create  the file attachment for this e-mail message.
            
            document.generateXPS();
            // document.generatePDF();
            
            Attachment attachment = new Attachment(filepath, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = attachment.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(filepath);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(filepath);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(filepath);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(attachment);
            

            // initiate smtp and add authentication
            SmtpClient client = new SmtpClient();
            client.Host = hostname;
            client.Port = getPort();
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            var authInfo = new System.Net.NetworkCredential(usrName, pass);
            client.Credentials = authInfo;
            //Send the message.
            try
            {
                client.Send(message);
                MessageBox.Show("Message Successfully Sent!");
                this.Close();
            }
            catch
            {
                MessageBox.Show("ERROR: Message Failed\nAuthentication information may be incorrect..");
            }
			
			
		}
		
		private String getHost()
		{
            switch (hostCombo.Text)
            {
                case "Yahoo": 
                    return "plus.smtp.mail.yahoo.com";
                case "Gmail": 
                    return "smtp.gmail.com";
                case "Live/Hotmail": 
                    return "smtp.live.com";
                default: 
                    return "";
            } 
		}
        private int getPort()
        {
            switch (hostCombo.Text)
            {
                case "Yahoo":
                    return 465;
                case "Gmail":
                    return 587;
                case "Live/Hotmail":
                    return 25;
                default:
                    return 0;
            }
        }

        private void sendClick(object sender, System.Windows.RoutedEventArgs e)
        {
        	sendMail();
			clearFields();

            try
            {
                File.Delete(filepath);
            }
            catch
            {
                MessageBox.Show("ERROR: Failed to delete invoice.xps file from AppData");
            }
        }
		
		private void clearFields()
		{
			hostCombo.SelectedIndex = 0;
			usernameBox.Text = "";
			passwordBox.Password = "";
			toBox.Text = "";
			subjectBox.Text = "";
			messageBody.Text = "";
		}
        private Boolean verifyEmail(String input)
        {
            if(Regex.IsMatch(input, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" 
                + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase))
            {
                return true;
            }
            else
                return false;

        }




	}
}